package com.ysm.smfu.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.ysm.smfu.R;
import com.ysm.smfu.StatusBarCompat;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.utils.AMapUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.welcome.SharedConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/10/9.
 */
public class GDActivity extends Activity implements AMap.OnCameraChangeListener {

    @BindView(R.id.map)
    MapView fragmentBdMapView;
    @BindView(R.id.fragment_bdList)
    ListView fragmentBdList;
    @BindView(R.id.bdmap_search)
    EditText bdmapSearch;
    @BindView(R.id.fragment_bdmap_search)
    TextView fragment_bdmap_search;

    @BindView(R.id.overLay)
    ImageView overLay;

    //    默认显示页面0
    private int pageNum;
    private AMap aMap;
    private PoiSearch.Query query;
    private MyAdapter adapter;
    private MarkerOptions markerOption;
    private UiSettings uiSettings;
    private AnimationDrawable animationDrawable;
    private List<PoiItem> pois;
    private String city;
    private PoiSearch poiSearch;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_gdmap);
        ButterKnife.bind(this);
        fragmentBdMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = fragmentBdMapView.getMap();
        }
        SharedPreferences sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        city = sp.getString(SpKey.BDLOC, "");
        String lat = sp.getString(SpKey.LAT, "");
        String lon = sp.getString(SpKey.LON, "");
//        进入时，默认搜索定位所得坐标周边
        if (!(TextUtils.isEmpty(lat) && TextUtils.isEmpty(lon))) {
            double lont = Double.parseDouble(lon);
            double latl = Double.parseDouble(lat);
            search("", new LatLonPoint(latl, lont));
        }

//        隐藏缩放控件
        uiSettings = aMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false);
        // 屏幕改变监听
        aMap.setOnCameraChangeListener(this);
        initData();
        initListener();
        initTopBar();
    }

    private void initTopBar() {
        StatusBarCompat.compat(this, getResources().getColor(R.color.green));
    }

    private void initData() {
        adapter = new MyAdapter();
        fragmentBdList.setAdapter(adapter);
    }

    private void initListener() {
        //        点击开始搜索
        fragment_bdmap_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keyWord = bdmapSearch.getText().toString().trim();
                if (TextUtils.isEmpty(keyWord)) {
                    ToastUtils.showToast("地址不能为空");
                } else {
                    search(keyWord, null);
                }
                UIUtils.hideKeyboard(GDActivity.this);
            }
        });

//        搜索结果条目点击事件
        fragmentBdList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                点击返回到商户选择页面，并携带经纬度信息和详细地址信息
                Intent intent = new Intent();
                if (poiItems.size() > 0 && poiItems.get(position) != null) {
                    intent.putExtra("title", poiItems.get(position).getTitle());
                    intent.putExtra("snippet", poiItems.get(position).getSnippet());
                    intent.putExtra("latlonpoint", poiItems.get(position).getLatLonPoint());
                } else {
                    intent.putExtra("title", "");
                    intent.putExtra("snippet", "");
                    intent.putExtra("latlonpoint", new LatLonPoint(39.906901, 116.397972));
                }
                setResult(201, intent);
                finish();
            }
        });

        //        Marker点击事件
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
                        .position(marker.getPosition())
                        .title(marker.getTitle())
                        .snippet(marker.getSnippet())
                        .draggable(true);
                marker = aMap.addMarker(markerOption);
                marker.showInfoWindow();
//                刷新listView显示
                LatLonPoint latLonPoint = new LatLonPoint(marker.getPosition().latitude, marker.getPosition().longitude);
                PoiItem poiItem = new PoiItem("", latLonPoint, marker.getTitle(), marker.getSnippet());
                poiItems = new ArrayList<PoiItem>();
                poiItems.add(poiItem);
                adapter.notifyDataSetChanged();

//                更新地图中心点
                CameraUpdate cameraupdate = CameraUpdateFactory.changeLatLng(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()));
                aMap.animateCamera(cameraupdate, 500, null);
                return true;
            }
        });
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
//        移动结束后中心点坐标
        LatLng target = cameraPosition.target;
        search("", AMapUtil.convertToLatLonPoint(target));
    }


    //    搜索结果条目
    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            int size = poiItems.size();
            if (size == 0) {
                size = 1;
            }
            return size;
        }

        @Override
        public Object getItem(int position) {
            return poiItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(UIUtils.getContext(), R.layout.gdmap_item, null);
            }
            TextView textView = (TextView) convertView.findViewById(R.id.text);
            TextView textView1 = (TextView) convertView.findViewById(R.id.text1);
            ImageView bd_list_img = (ImageView) convertView.findViewById(R.id.bd_list_img);
//            poiItems.get(position).getCityName()+ poiItems.get(position).getSnippet()
            if (poiItems.size() == 0) {
                textView.setText("当前位置没有检索到有效信息");
                textView1.setText("");
                bd_list_img.setVisibility(View.GONE);
            } else {
                bd_list_img.setVisibility(View.VISIBLE);
                PoiItem poiItem = poiItems.get(position);
                textView1.setText(poiItem.getTitle());
                String snippet = poiItem.getSnippet();
                textView.setText(snippet);
            }
            return convertView;
        }
    }

    boolean isSearch;

    public void search(String keyWord, LatLonPoint latLonPoint) {
        if (!TextUtils.isEmpty(keyWord)) {
            isSearch = true;
//            默认全国搜，不在定位城市搜
            query = new PoiSearch.Query(keyWord, "", "");
            query.setPageSize(10);// 设置每页最多返回多少条poiitem
            int currentPage = 0;
            query.setPageNum(currentPage);//设置查询页码
            poiSearch = new PoiSearch(this, query);
//            关键字搜索-poi检索
        }
        if (latLonPoint != null) {
            query = new PoiSearch.Query("", "", "");
            query.setPageSize(10);// 设置每页最多返回多少条poiitem
            int currentPage = 0;
            query.setPageNum(currentPage);//设置查询页码
            poiSearch = new PoiSearch(this, query);
            // 搜索周边
            poiSearch.setBound(new PoiSearch.SearchBound(latLonPoint, 1000));//设置周边搜索的中心点以及半径
        }
        poiSearch.setOnPoiSearchListener(poiSearchListener);
        poiSearch.searchPOIAsyn();
    }

    /**
     * 是否是第一次进入时的默认搜索
     */
    boolean isFirst = true;
    /**
     * 查询到的地址数据
     */
    private ArrayList<PoiItem> poiItems = new ArrayList<>();

    PoiSearch.OnPoiSearchListener poiSearchListener = new PoiSearch.OnPoiSearchListener() {
        @Override
        public void onPoiSearched(PoiResult result, int rCode) {
//                            dissmissProgressDialog();// 隐藏对话框
            if (rCode == 1000) {
                if (result != null && result.getQuery() != null) {// 搜索poi的结果
                    if (result.getQuery().equals(query)) {// 是否是同一条
                        // 取得搜索到的poiitems有多少页
                        poiItems = result.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                        List<SuggestionCity> suggestionCities = result
                                .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                        if (poiItems != null && poiItems.size() > 0) {
                            adapter.notifyDataSetChanged();
                            if (isFirst) {
                                CameraUpdate cameraupdate = CameraUpdateFactory.changeLatLng(AMapUtil.convertToLatLng(poiItems.get(0).getLatLonPoint()));
                                aMap.animateCamera(cameraupdate, 500, null);
                                isFirst = false;
                            }
                            if (isSearch) {
                                //更新屏幕中心点
                                CameraUpdate cameraupdate = CameraUpdateFactory.changeLatLng(AMapUtil.convertToLatLng(poiItems.get(0).getLatLonPoint()));
                                aMap.animateCamera(cameraupdate, 500, null);
                                isSearch = false;
                            }
                        } else if (suggestionCities != null
                                && suggestionCities.size() > 0) {
                            //得到建议城市
                            if (poiItems != null)
                                poiItems.clear();
                            adapter.notifyDataSetChanged();

                        } else {
                            if (poiItems != null)
                                poiItems.clear();
                            adapter.notifyDataSetChanged();
                        }
                    }
                } else {
                    Toast.makeText(GDActivity.this, "没有检索到有效信息", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(GDActivity.this, "搜索错误:" + rCode, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onPoiItemSearched(PoiItem poiItem, int i) {

        }
    };

    public void back(View view) {
        UIUtils.hideKeyboard(this);
        Intent intent = new Intent();
        intent.putExtra("title", "");
        intent.putExtra("snippet", "");
        intent.putExtra("latlonpoint", new LatLonPoint(39.906901, 116.397972));
        setResult(201, intent);
        finish();
    }

    /**
     * 管理地图生命周期
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        fragmentBdMapView.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        fragmentBdMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        fragmentBdMapView.onPause();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("title", "");
        intent.putExtra("snippet", "");
        intent.putExtra("latlonpoint", new LatLonPoint(39.906901, 116.397972));
        setResult(201, intent);
        finish();
    }


    class MyPoint {
        String name;
        double lat;
        double lont;
    }
}
